using System.Timers;
using CoreGraphics;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using UIKit;

namespace libmp
{
    public class VCLoginController : UIViewController
    {
        static ILog logger = mb.ServiceLocator.Instance.Get<ILog>();
        VCSetting setting;

        public VCLoginController(VCSetting vcSetting)
        {
            TabBarItem = new UITabBarItem("设置", null, 0);
            setting = vcSetting;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            CreateView();
        }

        private void CreateView()
        {
            var bkView = new UIView() { BackgroundColor = Util.MainBKColor };
            bkView.SetParent(View).MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Left.Right.Bottom.EqualTo(View);
            });
            var mainView = new UIView();
            mainView.SetParent(View);
            mainView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Bottom.EqualTo(View);
            });
            createTopBar(mainView);
            CreateAdvenise(mainView);
            createContents(mainView);
            createButton(mainView);
        }
        private void createTopBar(UIView mainView)
        {
            var btnPicWidth = 15;
            var btnPicHeight = 15;
            var topBarView = new UIView();
            topBarView.BackgroundColor = UIColor.FromRGB(251, 114, 153);
            topBarView.SetParent(mainView);
            topBarView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Height.EqualTo(NSObject.FromObject(48));
            });

            var topBarLeftView = new UIView();
            topBarLeftView.SetParent(topBarView);
            topBarLeftView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject(10));
                m.Top.EqualTo(topBarView);
                m.Bottom.EqualTo(topBarView);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });

            var leftButton1 = new UIButton();
            leftButton1.Frame = new CGRect(0, 14, btnPicWidth + 30, btnPicHeight + 5);
            leftButton1.SetParent(topBarLeftView);
            var leftButton1ImageView = new UIImageView();
            var imgoperationArrow1 = UIImage.FromFile($"{App.HotStorageRoot}/res/user/Fanhui.png");
            leftButton1ImageView.Image = new UIImage(imgoperationArrow1.CGImage, 2, UIImageOrientation.Up);
            leftButton1ImageView.SetParent(leftButton1);
            leftButton1ImageView.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(leftButton1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(5));
                m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
                m.Width.EqualTo(NSObject.FromObject(btnPicWidth / 2));
            });
            var leftButton2Label = new UILabel();
            leftButton2Label.Text = "返回";
            leftButton2Label.Font = UIFont.SystemFontOfSize(12);
            leftButton2Label.SetParent(leftButton1);
            leftButton2Label.TextColor = UIColor.White;
            leftButton2Label.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(leftButton1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(20));
                m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
                m.Width.EqualTo(NSObject.FromObject(btnPicWidth + 20));
            });
            leftButton1.TouchUpInside += (s, e) =>
            {
                logger.Log("返回====>");
                AppDelegate.Instance.NavController.PopViewController(false);
            };

            // var leftButton2 = new UIButton();
            // leftButton2.Frame = new CGRect(btnPicWidth + 15, 14, btnPicWidth + 20, btnPicHeight + 5);
            // leftButton2.SetParent(topBarLeftView);
            // var leftButton2Label = new UILabel();
            // leftButton2Label.Text = "关闭";
            // leftButton2Label.SetParent(leftButton2);
            // leftButton2Label.MakeConstraints(m =>
            // {
            //     m.CenterY.EqualTo(leftButton2.CenterY());
            //     m.CenterX.EqualTo(leftButton2.CenterX());
            //     m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
            //     m.Width.EqualTo(NSObject.FromObject(btnPicWidth + 20));
            // });
            // leftButton2.SetParent(topBarLeftView);

            var topBarMiddleView = new UIView();
            topBarMiddleView.SetParent(topBarView);
            topBarMiddleView.MakeConstraints(m =>
            {
                m.Left.EqualTo(topBarLeftView.Right());
                m.Top.EqualTo(topBarView);
                m.Bottom.EqualTo(topBarView);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });

            var middleLabel = new UILabel();
            middleLabel.Text = "登录";
            middleLabel.Font = UIFont.BoldSystemFontOfSize(18);
            middleLabel.SetParent(topBarMiddleView);
            middleLabel.TextColor = UIColor.White;
            middleLabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(topBarMiddleView.CenterY());
                m.CenterX.EqualTo(topBarMiddleView.CenterX());
            });

            var topBarRightView = new UIView();
            topBarRightView.SetParent(topBarView);
            topBarRightView.MakeConstraints(m =>
            {
                m.Left.EqualTo(topBarMiddleView.Right());
                m.Top.EqualTo(topBarView);
                m.Bottom.EqualTo(topBarView);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });
        }
        private void CreateAdvenise(UIView mainView)
        {
            var adverisePicView = new UIView();
            adverisePicView.SetParent(mainView);
            adverisePicView.BackgroundColor = UIColor.FromRGB(245, 209, 219);
            adverisePicView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject(0));
                m.Top.EqualTo(NSObject.FromObject(48));
                m.Right.EqualTo(NSObject.FromObject(0));
                m.Height.EqualTo(NSObject.FromObject(140));
            });
            // var adImg = libmp.DataStore.store.onlineConfig.adImages[0];
            // Util.createAdverse(adImg, adverisePicView);
        }
        UITextField telphoneTextField = new UITextField();
        //UILabel wrongTelphoneMsgLabel = new UILabel();
        UITextField passwordTextField = new UITextField();
        //UILabel wrongPasswordMsgLabel = new UILabel();
        UILabel msgLabel = new UILabel();
        private void createContents(UIView mainView)
        {

            var msgLabelView = new UIView();
            msgLabelView.SetParent(mainView);
            msgLabelView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(NSObject.FromObject(200));
                m.Height.EqualTo(NSObject.FromObject(20));
            });
            msgLabel.SetParent(msgLabelView);
            msgLabel.TextAlignment = UITextAlignment.Center;
            msgLabel.Frame = new CGRect(0, 0, View.Bounds.Width, 15);

            var EditTextView = new UIView();
            EditTextView.SetParent(mainView);
            EditTextView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(NSObject.FromObject(220));
                m.Height.EqualTo(NSObject.FromObject(96));
            });

            createTextField(EditTextView, telphoneTextField, "在这里输入手机号", false, 0);

            createTextField(EditTextView, passwordTextField, "请输入密码", true, 1);

        }

        private void createTextField(UIView EditTextView, UITextField textFieldName, string placeholderString, bool ifPassword, int i)
        {
            string[] pics = new string[]
            {
                "Land_character.png",
                "Land_Password.png"
            };
            var oneTextFieldViewHeight = 48;
            var textFieldWidth = View.Bounds.Width;
            var oneTextFieldView = new UIView();
            oneTextFieldView.BackgroundColor = UIColor.White;
            oneTextFieldView.SetParent(EditTextView);
            oneTextFieldView.MakeConstraints(m =>
            {
                m.Top.EqualTo(NSObject.FromObject(i * (oneTextFieldViewHeight + 0.5)));
                m.Left.EqualTo(NSObject.FromObject(0));
                m.Height.EqualTo(NSObject.FromObject(oneTextFieldViewHeight));
                m.Right.EqualTo(NSObject.FromObject(0));
            });

            var textFieldImageView = new UIImageView();
            var imgoperationArrow1 = UIImage.FromFile($"{App.HotStorageRoot}/res/user/" + pics[i]);
            textFieldImageView.Image = new UIImage(imgoperationArrow1.CGImage, 2, UIImageOrientation.Up);
            textFieldImageView.SetParent(oneTextFieldView);
            textFieldImageView.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(oneTextFieldView.CenterY());
                m.Left.EqualTo(NSObject.FromObject(20));
                m.Height.EqualTo(NSObject.FromObject(15));
                m.Width.EqualTo(NSObject.FromObject(12));
            });

            textFieldName.SetParent(oneTextFieldView);
            textFieldName.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(oneTextFieldView.CenterY());
                m.Left.EqualTo(NSObject.FromObject(50));
                m.Height.EqualTo(NSObject.FromObject(20));
                m.Width.EqualTo(NSObject.FromObject(textFieldWidth - 100));
            });
            textFieldName.Placeholder = placeholderString;
            textFieldName.Font = UIFont.SystemFontOfSize(14);
            textFieldName.AutocapitalizationType = UITextAutocapitalizationType.None;
            textFieldName.AutocorrectionType = UITextAutocorrectionType.No;
            textFieldName.SecureTextEntry = ifPassword;
            textFieldName.ReturnKeyType = UIReturnKeyType.Done;
            textFieldName.Delegate = new MyUITextFieldDelegate()
            {
                MyShouldReturn = (tf) =>
                {
                    tf.ResignFirstResponder();
                    return true;
                }
            };

        }

        private void createButton(UIView mainView)
        {
            var bWidth = View.Bounds.Width - 50;
            var buttonView = new UIView();
            buttonView.SetParent(mainView);
            //buttonView.BackgroundColor = UIColor.Red;
            buttonView.MakeConstraints(m =>
            {
                m.Width.EqualTo(NSObject.FromObject(bWidth));
                m.CenterX.EqualTo(View.CenterX());
                m.Top.EqualTo(NSObject.FromObject(330));
                m.Height.EqualTo(NSObject.FromObject(50));
            });

            var registerButonView = new UIView();
            registerButonView.SetParent(buttonView);
            registerButonView.BackgroundColor = UIColor.White;
            registerButonView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject(0));
                m.Top.EqualTo(NSObject.FromObject(0));
                m.Width.EqualTo(NSObject.FromObject((bWidth - 20) / 2));
                m.Height.EqualTo(NSObject.FromObject(50));
            });
            registerButonView.Layer.CornerRadius = 6;
            registerButonView.ClipsToBounds = true;
            registerButonView.Layer.BorderWidth = 0;

            var registerButton = new UIButton();
            registerButton.Frame = new CGRect(0, 0, (bWidth - 20) / 2, 50);
            registerButton.SetParent(registerButonView);

            var registerLabel = new UILabel();
            registerLabel.Text = "注册";
            registerLabel.SetParent(registerButton);
            registerLabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(registerButonView.CenterY());
                m.CenterX.EqualTo(registerButonView.CenterX());
                m.Height.EqualTo(NSObject.FromObject(20));
                m.Width.EqualTo(NSObject.FromObject(35));
            });
            registerButton.TouchUpInside += (s, e) =>
            {
                logger.Log("前往注册页面");
                AppDelegate.Instance.NavController.PushViewController(new VCRegisterController(setting), false);
            };

            var loginButonView = new UIView();
            loginButonView.SetParent(buttonView);
            loginButonView.BackgroundColor = UIColor.FromRGB(251, 114, 153);
            loginButonView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject((bWidth - 20) / 2 + 20));
                m.Top.EqualTo(NSObject.FromObject(0));
                m.Width.EqualTo(NSObject.FromObject((bWidth - 20) / 2));
                m.Height.EqualTo(NSObject.FromObject(50));
            });
            loginButonView.Layer.CornerRadius = 6;
            loginButonView.ClipsToBounds = true;
            loginButonView.Layer.BorderWidth = 0;
            var loginButton = new UIButton();
            loginButton.Frame = new CGRect(0, 0, (bWidth - 20) / 2, 50);
            loginButton.SetParent(loginButonView);
            var loginLabel = new UILabel();
            loginLabel.Text = "登录";
            loginLabel.TextColor = UIColor.White;
            loginLabel.SetParent(loginButton);
            loginLabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(loginButonView.CenterY());
                m.CenterX.EqualTo(loginButonView.CenterX());
                m.Height.EqualTo(NSObject.FromObject(20));
                m.Width.EqualTo(NSObject.FromObject(35));
            });
            loginButton.TouchUpInside += (s, e) =>
            {
                logger.Log("登录操作");
                loginSubmit();
            };
        }
        private void loginSubmit()
        {
            bool ifCanSubmit = true;
            initWrongMsg();
            string telphoneString = telphoneTextField.Text;
            string passwordString = passwordTextField.Text;
            if (verifyTelephone() == false)
            {
                ifCanSubmit = false;
            }
            else if (passwordString.Length < 6)
            {
                msgLabel.Text = "密码不能少于6位";
                msgLabel.TextColor = UIColor.Red;
                ifCanSubmit = false;
            }
            else if (passwordString.Length > 15)
            {
                msgLabel.Text = "密码不能大于15位";
                msgLabel.TextColor = UIColor.Red;
                ifCanSubmit = false;
            }

            if (ifCanSubmit)
            {
                logger.Log("验证通过，执行登录操作····");
                var lastid = User.me.id;
                setting.UserLogin(telphoneString, passwordString, (requestInfo) =>
                {
                    var res = showMsgView(requestInfo);
                    if (res)
                    {
                        //VCSetting.shadowView.Alpha = 0;
                        AppDelegate.Instance.NavController.PopViewController(false);
                        setting.updateUserInfoView();
                    }
                });
            }
        }
        private void showMsgInfoAlpha()
        {
            var second = 1500;
            msgLabel.Alpha = 1f;
            var testTimer = new Timer() { Interval = 10, Enabled = true };
            testTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                if (second < 1)
                {
                    (sender as Timer).Stop();
                }
                this.InvokeOnMainThread(() =>
                {
                    if (second < 200)
                    {
                        msgLabel.Alpha = (float) second / 200;
                    }
                    second--;
                });
            };
        }
        bool showMsgView(UserInfoData requestInfo)
        {
            if (requestInfo.error.Length > 0)
            {
                msgLabel.Text = requestInfo.error;
                msgLabel.TextColor = UIColor.Red;
                showMsgInfoAlpha();
                return false;
            }
            else if (requestInfo.msg.Length > 0)
            {
                libmp.User.me.token = requestInfo.token;
                libmp.User.me.Save();
                msgLabel.Text = requestInfo.msg;
                msgLabel.TextColor = UIColor.FromRGB(50, 110, 0);
                showMsgInfoAlpha();
            }
            return true;
        }
        private bool verifyTelephone()
        {
            string telphoneString = telphoneTextField.Text;
            if (telphoneString.Length == 0)
            {
                msgLabel.Text = "手机号码必填";
                msgLabel.TextColor = UIColor.Red;
                return false;
            }
            else if (!Util.IsPhoneNo(telphoneString))
            {
                msgLabel.Text = "手机号码错误";
                msgLabel.TextColor = UIColor.Red;
                return false;
            }
            return true;
        }
        private void initWrongMsg()
        {
            msgLabel.Text = "";
        }
    }

}